import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:base_lib/utils/shared_preference_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';


//HTTP请求的函数返回值为异步控件Future
Future<String> get(String url) async {
  var httpClient = new HttpClient();
  var request = await httpClient.getUrl(Uri.parse(url));
  var response = await request.close();
  return await response.transform(utf8.decoder).join();
}

/// 通过url判断是否存在缓存，url 是缓存数据的key
Future<String> getCacheData(String url) async {
  ///先通过url获取缓存中的数据
  var cacheData = await SPUtil.getString(url);
  if (cacheData != null) {
    print("----首页走缓存---");
    return json.decode(cacheData);
  } else {
    Future<String> join = get(url);
    join.then<void>((String data) {
      ///缓存网络请求的数据
      SPUtil.putString(url, json.encode(data));
      print("-------请求网络数据");
    });
    return join;
  }
}

///异常处理
Widget buildExceptionIndicator(String message) {
  return new Column(
    mainAxisAlignment: MainAxisAlignment.center,
    children: <Widget>[
      new Align(
        alignment: Alignment.center,
        child: new Column(
          children: <Widget>[
            new Icon(
              Icons.error,
              size: 50.0,
              color: Colors.grey,
            ),
            new Container(
              padding: EdgeInsets.only(top: 20.0),
              child: new Text(
                message,
                style: const TextStyle(color: Colors.grey),
              ),
            )
          ],
        ),
      ),
    ],
  );
}

Widget buildPageEmpty({String des = '暂无数据'}) {
  return Container(
    //错误页面中心可以自己调整
    padding: EdgeInsets.fromLTRB(0, 0, 0, 200),
    color: Colors.white,
    width: double.infinity,
    height: double.infinity,
    child: Center(
      child: Container(
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Icon(
              Icons.cloud,
              color: Colors.black12,
              size: 100,
            ),
            Container(
              margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
              child: Text(
                des,
                style: TextStyle(color: Colors.black54),
              ),
            )
          ],
        ),
      ),
    ),
  );
}

///正在加载
Widget buildLoadingIndicator() {
  return new Center(
    child: new CupertinoActivityIndicator(),
  );
}

Widget buildFooterLoading() {
  //加载时显示loading
  return Container(
    padding: const EdgeInsets.all(16.0),
    alignment: Alignment.center,
    child: SizedBox(
        width: 24.0,
        height: 24.0,
        child: CircularProgressIndicator(strokeWidth: 2.0)),
  );
}

Widget buildFooterNoMore() {
  //加载时显示loading
  return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.all(16.0),
      child: Text(
        "没有更多了",
        style: TextStyle(color: Colors.grey),
      ));
}
